import React, { useEffect, useState, useCallback } from 'react';
import { connect } from 'umi';
import { Table, Form, Input, Card, Button, Tooltip, Modal, Icon, message, Tag, Typography, Checkbox } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { history } from 'umi'
import cn from 'classnames';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import authHelper from '@/utils/auth/helper';
import { useRequest } from '@/hooks';
import { eventTrack } from '@/utils/track';
import { companyColumns, departmentColumns, getPostColumns } from './columns.jsx';
import styles from './index.less';
import {
    delectDuty,
    getOrgList,
    getPostList,
    postChangeDeleteCheck,
    getOrganizationByCode,
    getOrgTotalPlanNum // 岗位的编制统计数据, 因为岗位的统计规则比较复杂
} from '../services';

const { checkCode } = authHelper;
const { confirm } = Modal;

const OrgManage = ({ location, form }) => {
    const { getFieldDecorator, getFieldsValue } = form;
    const { pathname = '', query } = location;

    const [parentAuditStatus, setParentAuditStatus] = useState(null);

    const [orgType, setOrgType] = useState('');
    const [tableType, setTableType] = useState('');
    const [tableColumns, setTableColumns] = useState([]);

    const [loading, setLoading] = React.useState(false);
    const [dataSource, setDataSource] = React.useState([]);

    const { run: baseInfoRequestRun, cancel: baseInfoRequestCancel, data: baseInfoRequestData } = useRequest(
        orgType === '岗位管理' ? getOrgTotalPlanNum : getOrganizationByCode,
        {
            manual: true
        }
    );

    useEffect(() => {
        if (query) {
            // 从 url 参数获得上级页面传过来的审批状态
            setParentAuditStatus(Number(query?.auditStatus || 0));
            // 获取基础数据
            if (query.organizationCode) {
                baseInfoRequestRun({ organizationCode: query.organizationCode });
            }
        }
        return () => {
            baseInfoRequestCancel();
        };
    }, [baseInfoRequestCancel, baseInfoRequestRun, query]);

    // 过滤数据
    const filterTree = tree =>
        tree.map(({ children, ...props }) => {
            if (children && children.length > 0) {
                return { children: filterTree(children), ...props };
            }
            return { children: '', ...props, organizationPermissions: query?.organizationPermissions };
        });

    // 溢出处理
    const ellipsisText = name => (
        <Typography.Text
            style={{
                marginBottom: 0,
                paddingLeft: 0,
                maxWidth: 300
            }}
            title={name}
            ellipsis
        >
            {name || ''}
        </Typography.Text>
    );

    // 顶部数据统计
    const renderTopDom = useCallback(() => {
        const baseInfo = baseInfoRequestData ? baseInfoRequestData.data : null;

        // 审批状态标识
        const auditStatusTag = () =>
            parentAuditStatus === 1 && (
                <Tag color="orange" style={{ marginLeft: 10 }}>
                    审批中
                </Tag>
            );

        if (orgType === '公司管理') {
            return (
                <p>
                    {orgType}
                    <span> 机构： {ellipsisText(query.organizationName)} </span>
                    {auditStatusTag()}
                    <span>公司总数：{baseInfo?.companyNumber || 0}</span>
                </p>
            );
        }
        if (orgType === '直属部门管理') {
            return (
                <p>
                    {orgType} <span>上级机构： {ellipsisText(query.organizationName)}</span>
                    {auditStatusTag()}
                    <span>部门总数：{baseInfo?.directDepartmentNum || 0}</span>
                </p>
            );
        }
        if (orgType === '下属部门管理') {
            return (
                <p>
                    {orgType} <span>上级机构： {ellipsisText(query.organizationName)}</span>
                    {auditStatusTag()}
                    <span>部门总数：{baseInfo?.underDepartmentNumber || 0}</span>
                </p>
            );
        }
        if (orgType === '岗位管理') {
            return (
                <p>
                    {orgType} <span>机构： {ellipsisText(query.organizationName)}</span>
                    {auditStatusTag()}
                    <span>总编制：{baseInfo?.planNum || 0}</span>
                </p>
            );
        }
        return '';
    }, [baseInfoRequestData, orgType, parentAuditStatus, query.organizationName]);

    // 请求数据
    const fetchList = useCallback(
        async payload => {
            const fixed = {
                countEmployeeNumFlag: 1,
                getEmployeeFlag: 1,
                showNumberFlag: 1,
                showTreeFlag: 0
            };
            const param = getFieldsValue();

            setLoading(true);
            const res = await getOrgList({ ...payload, ...fixed, ...param });
            if (res.code === 10000) {
                setDataSource(res.data);
            } else {
                message.error(res.msg);
            }
            setLoading(false);
        },
        [getFieldsValue]
    );

    // 查询编制数据
    const fetchPostList = useCallback(
        async payload => {
            const param = getFieldsValue();
            setLoading(true);
            const res = await getPostList({ ...payload, ...param });
            if (res.code === 10000) {
                setDataSource(res.data);
            } else {
                message.error(res.msg);
            }
            setLoading(false);
        },
        [getFieldsValue]
    );

    // 根据参数获取表格数据
    const getParams = useCallback(() => {
        if (tableType !== '') {
            let payload = {};
            if (tableType === 'company') {
                payload = {
                    parentOrganizationPathLike: query.organizationPath,
                    organizationType: query.organizationType
                };
                fetchList(payload);
            }
            if (tableType === 'department') {
                payload = {
                    parentOrganizationPath: query.organizationPath,
                    organizationType: query.organizationType
                };
                fetchList(payload);
            }
            if (tableType === 'subordinate') {
                payload = {
                    parentOrganizationPathLike: query.organizationPath,
                    organizationType: query.organizationType
                };
                fetchList(payload);
            }
            if (tableType === 'postList') {
                payload = {
                    organizationPath: query.organizationPath,
                    organizationCode: query.organizationCode
                };
                fetchPostList(payload);
            }
        }
    }, [fetchList, fetchPostList, query, tableType]);

    // 查询
    const handleSubmit = e => {
        e.preventDefault();
        getParams();
        const param = getFieldsValue();
        if (tableType === 'company') {
            eventTrack({
                eventName: 'personnel_management_organization_company_manage_search_submit_click',
                pageName: 'personnel_management_organization',
                eventProps: {
                    click_context: `公司:${param.organizationNameLike || '空'},主管:${param.employeeNameLike || '空'}`
                }
            });
        } else if (tableType === 'department' || tableType === 'subordinate') {
            eventTrack({
                eventName: 'personnel_management_organization_department_manage_search_submit_click',
                pageName: 'personnel_management_organization',
                eventProps: {
                    click_context: `部门:${param.organizationNameLike || '空'},主管:${param.employeeNameLike || '空'}`
                }
            });
        } else if (tableType === 'postList') {
            eventTrack({
                eventName: 'personnel_management_organization_post_list_search_submit_click',
                pageName: 'personnel_management_organization',
                eventProps: {
                    click_context: `名称:${param.dutyAliasLike || '空'}`
                }
            });
        }
    };

    const handleOk = useCallback(async (text, record) => {
        const { dutyCode } = record;
        // 删除前校验
        const { msg, code: delCheckCode } = await postChangeDeleteCheck(dutyCode);
        if (delCheckCode === 10000) {
            const params = {
                dutyCode,
                operationType: 2
            };
            const { code, data: id, msg: subMsg } = await delectDuty(params);

            if (code === 10000) {
                // 流程不存在提示
                const { workFlowUrl, workFlowErrorMsg } = await hasWorkFlowByType('PostChange', false);
                if (!workFlowUrl) {
                    Modal.error({
                        title: '删除失败',
                        icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                        content: workFlowErrorMsg,
                        okText: '我知道了'
                    });
                    return;
                }

                history.push(`${workFlowUrl}${id}`);
            } else {
                message.error(subMsg);
            }
        } else {
            Modal.error({
                title: '删除失败',
                icon: <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />,
                content: msg,
                okText: '我知道了'
            });
        }
    }, []);

    useEffect(() => {
        if (pathname.includes('organization/companyManage')) {
            setOrgType('公司管理');
            setTableType('company');
            setTableColumns(companyColumns);
        }
        if (pathname.includes('organization/departmentManage')) {
            setOrgType('直属部门管理');
            setTableType('department');
            setTableColumns(departmentColumns);
        }
        if (pathname.includes('organization/subordinateManage')) {
            setOrgType('下属部门管理');
            setTableType('subordinate');
            setTableColumns(departmentColumns);
        }
        if (pathname.includes('organization/postList')) {
            setOrgType('岗位管理');
            setTableType('postList');
            const operation = {
                title: '操作',
                dataIndex: 'operation',
                width: 170,
                fixed: 'right',
                render: (text, record) =>
                    Number(query?.organizationPermissions) === 1 && (
                        <React.Fragment>
                            {checkCode('office:orgs:organization:duty:edit') && (
                                <Tooltip title="编辑">
                                    <i
                                        disabled={record.auditStatus !== undefined && record.auditStatus !== 2}
                                        className={cn('iconfont iconlistfunction_edit_icon_default', styles.icon)}
                                        onClick={async () => {
                                            await eventTrack({
                                                eventName: 'personnel_management_organization_post_list_operator_click',
                                                pageName: 'personnel_management_organization',
                                                eventProps: {
                                                    click_context: `${record.dutyAlias}-编辑`
                                                }
                                            });
                                            history.push({
                                                pathname: '/office/personnelManagement/organization/postedit',
                                                query: {
                                                    dutyCode: record.dutyCode,
                                                    organizationCode: record.organizationCode,
                                                    organizationPath: record.organizationPath,
                                                    organizationName: record.organizationName
                                                }
                                            });
                                        }}
                                    />
                                </Tooltip>
                            )}

                            {checkCode('office:orgs:organization:duty:recruit') && (
                                <Tooltip title="提交招聘需求">
                                    <i
                                        disabled={record.auditStatus !== undefined && record.auditStatus !== 2}
                                        className={cn('iconfont icontijiaozhaopinxuqiu', styles.icon)}
                                        onClick={async () => {
                                            await eventTrack({
                                                eventName: 'personnel_management_organization_post_list_operator_click',
                                                pageName: 'personnel_management_organization',
                                                eventProps: {
                                                    click_context: `${record.dutyAlias}-提交招聘需求`
                                                }
                                            });
                                            history.push({
                                                pathname: '/office/personnelManagement/recruitment/demand/apply',
                                                query: {
                                                    dutyCode: record.dutyCode,
                                                    organizationCode: record.organizationCode
                                                }
                                            });
                                        }}
                                    />
                                </Tooltip>
                            )}

                            {checkCode('office:orgs:organization:duty:delete') && (
                                <Tooltip title="删除">
                                    <i
                                        disabled={record.auditStatus !== undefined && record.auditStatus !== 2}
                                        className={cn(
                                            'iconfont iconlistfunction_delete_icon_default',
                                            styles.icon,
                                            styles.delect
                                        )}
                                        onClick={async () => {
                                            await eventTrack({
                                                eventName: 'personnel_management_organization_post_list_operator_click',
                                                pageName: 'personnel_management_organization',
                                                eventProps: {
                                                    click_context: `${record.dutyAlias}-删除`
                                                }
                                            });
                                            const confirmModal = confirm({
                                                title: '确定删除？',
                                                icon: (
                                                    <Icon type="close-circle" theme="filled" style={{ color: 'red' }} />
                                                ),
                                                okButtonProps: {
                                                    disabled: true
                                                },
                                                content: (
                                                    <div className={styles.deleteInfo}>
                                                        <p>删除此岗位前请先做确认：</p>
                                                        <p>· 此岗位是否有在职员工？</p>
                                                        <p>· 此岗位是否正在进行招聘？</p>
                                                        <p>· 此岗位是否有正在入职的员工？</p>
                                                        <p>上述情况皆无，才能够删除此岗位</p>
                                                        <div>
                                                            <Checkbox
                                                                onChange={e => {
                                                                    confirmModal.update({
                                                                        okButtonProps: {
                                                                            disabled: !e.target.checked
                                                                        }
                                                                    });
                                                                }}
                                                            >
                                                                确认删除该岗位
                                                            </Checkbox>
                                                        </div>
                                                    </div>
                                                ),
                                                okText: '确定',
                                                cancelText: '取消',
                                                onOk: () => handleOk(text, record)
                                            });
                                        }}
                                    />
                                </Tooltip>
                            )}
                        </React.Fragment>
                    )
            };
            const postColumns = getPostColumns(query);
            if (postColumns.length === 6) {
                postColumns.push(operation);
            } else {
                postColumns.pop();
                postColumns.push(operation);
            }

            setTableColumns(postColumns);
        }
    }, [fetchPostList, handleOk, pathname, query]);

    // 处理新增按钮的功能
    const handleAdd = useCallback(() => {
        const urlQuery = {
            organizationName: query.organizationName,
            organizationPath: query.organizationPath,
            organizationCode: query.organizationCode
        };
        if (tableType === 'company') {
            history.push({
                pathname: '/office/personnelManagement/organization/companyadd',
                query: { ...urlQuery }
            });
        }
        if (tableType === 'department') {
            history.push({
                pathname: '/office/personnelManagement/organization/departmentadd',
                query: { ...urlQuery }
            });
        }
        if (tableType === 'subordinate') {
            history.push({
                pathname: '/office/personnelManagement/organization/departmentadd',
                query: { ...urlQuery }
            });
        }
        if (tableType === 'postList') {
            history.push({
                pathname: '/office/personnelManagement/organization/postadd',
                query: { ...urlQuery }
            });
        }
    }, [query, tableType]);

    // 1 为label名称  2为placeholder
    const getFormItemName = useCallback(
        type => {
            if (type === 1) {
                if (tableType === 'company') {
                    return '公司';
                }
                if (tableType === 'department' || tableType === 'subordinate') {
                    return '部门';
                }
            }
            if (type === 2) {
                if (tableType === 'company') {
                    return '请输入公司';
                }
                if (tableType === 'department' || tableType === 'subordinate') {
                    return '请输入部门';
                }
            }
            return '';
        },
        [tableType]
    );

    useEffect(() => {
        getParams();
    }, [getParams]);

    return (
        <PageHeaderWrapper>
            <div style={{ background: '#fff' }}>
                <div className={styles.orgManage}>
                    <div className={styles.headerPanel}>{renderTopDom()}</div>
                    <div>
                        {Number(query.organizationPermissions) === 1 ? (
                            <>
                                {checkCode('office:orgs:organization:duty:new') && (
                                    <Button
                                        type="primary"
                                        disabled={parentAuditStatus === 1}
                                        onClick={async () => {
                                            handleAdd();
                                            if (tableType === 'company') {
                                                await eventTrack({
                                                    eventName:
                                                        'personnel_management_organization_company_manage_add_input_click',
                                                    pageName: 'personnel_management_organization'
                                                });
                                            } else if (tableType === 'department' || tableType === 'subordinate') {
                                                await eventTrack({
                                                    eventName:
                                                        'personnel_management_organization_department_manage_add_input_click',
                                                    pageName: 'personnel_management_organization'
                                                });
                                            } else if (tableType === 'postList') {
                                                await eventTrack({
                                                    eventName:
                                                        'personnel_management_organization_post_list_add_input_click',
                                                    pageName: 'personnel_management_organization'
                                                });
                                            }
                                        }}
                                    >
                                        新增
                                    </Button>
                                )}
                            </>
                        ) : null}
                    </div>
                </div>
                <Card bordered={false}>
                    <div
                        style={{
                            marginBottom: 16
                        }}
                    >
                        <Form onSubmit={handleSubmit} layout="inline" className={styles.formClass}>
                            {tableType === 'postList' ? null : (
                                <Form.Item label={getFormItemName(1)}>
                                    {getFieldDecorator('organizationNameLike')(
                                        <Input
                                            placeholder={getFormItemName(2)}
                                            allowClear
                                            onFocus={() => {
                                                if (tableType === 'company') {
                                                    eventTrack({
                                                        eventName:
                                                            'personnel_management_organization_company_manage_company_input_click',
                                                        pageName: 'personnel_management_organization'
                                                    });
                                                } else if (tableType === 'department' || tableType === 'subordinate') {
                                                    eventTrack({
                                                        eventName:
                                                            'personnel_management_organization_department_manage_department_input_click',
                                                        pageName: 'personnel_management_organization'
                                                    });
                                                }
                                            }}
                                        />
                                    )}
                                </Form.Item>
                            )}

                            {/* 岗位管理的搜索条件不同 */}
                            {tableType === 'postList' ? (
                                <Form.Item label="名称">
                                    {getFieldDecorator('dutyAliasLike')(
                                        <Input
                                            placeholder="请输入名称"
                                            allowClear
                                            onFocus={() => {
                                                eventTrack({
                                                    eventName:
                                                        'personnel_management_organization_post_list_name_input_click',
                                                    pageName: 'personnel_management_organization'
                                                });
                                            }}
                                        />
                                    )}
                                </Form.Item>
                            ) : (
                                <Form.Item label="主管">
                                    {getFieldDecorator('employeeNameLike')(
                                        <Input
                                            placeholder="请输入主管"
                                            allowClear
                                            onFocus={() => {
                                                if (tableType === 'company') {
                                                    eventTrack({
                                                        eventName:
                                                            'personnel_management_organization_company_manage_leader_input_click',
                                                        pageName: 'personnel_management_organization'
                                                    });
                                                } else if (tableType === 'department' || tableType === 'subordinate') {
                                                    eventTrack({
                                                        eventName:
                                                            'personnel_management_organization_department_manage_leader_input_click',
                                                        pageName: 'personnel_management_organization'
                                                    });
                                                }
                                            }}
                                        />
                                    )}
                                </Form.Item>
                            )}
                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    搜索
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <Table
                        className={styles.tableAui}
                        loading={loading}
                        defaultExpandAllRows
                        scroll={{ x: 'max-content' }}
                        columns={tableColumns}
                        dataSource={filterTree(dataSource)}
                        rowKey="id"
                        pagination={false}
                    />
                </Card>
            </div>
        </PageHeaderWrapper>
    );
};

export default connect()(Form.create()(OrgManage));
